package com.jl.aop;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Aspect
@Component
@Slf4j
public class JLMvcAop {

    // 切入点
    @Pointcut("@within(com.jl.annotation.JLMvc)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object doMethod(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed;
        String traceId = UUID.randomUUID().toString().replace("-", "");
        if (StringUtils.isEmpty(MDC.get("traceId"))) {
            MDC.put("traceId", traceId);
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        proceed = pjp.proceed();
        stopWatch.stop();
        return proceed;
    }

    // 例外通知
    @AfterThrowing(value = "pointCut()", throwing = "exc")
    public void finanlExce(JoinPoint joinPoint, Throwable exc) {
        MDC.clear();
    }

    @AfterReturning(value = "pointCut()", returning = "rtv")
    public void afterRetuExce(JoinPoint joinPoint, Object rtv) {
        MDC.clear();
    }

}
